﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using System.Data;

namespace IntelligentCMS
{

    /// <summary>
    /// A "hook" class for any plugins (.dll) assemblies we need to load.
    /// </summary>
    public class CMSPlugin
    {

       
        public CMSPlugin()
        {
           

        }

        /// <summary>
        /// Use this for an assembly (dll) that we need to add to the database.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="filename"></param>
        public CMSPlugin(string filename)
        {
            
            this.filename = filename;
            Add();


        }



        private string filename = string.Empty;
        private string name = string.Empty;
        
        private Assembly theAssembly = null;

        public void Load()
        {
            theAssembly = Assembly.LoadFile(filename);

        }

        public void LoadFromDB(string name)
        {
            CMSDbDataLayer newDataLayer = new CMSDbDataLayer(string.Empty, CMSDbDataHelper.Microsoft);
            newDataLayer.AddQuery("SELECT [FileName] FROM CMS_Plugins WHERE [PluginID] = '" + name + "'");
            newDataLayer.SelectQuery = true;
            newDataLayer.Execute();

            filename = newDataLayer.Data.Rows[0].ItemArray[0].ToString();
            Load();

        }

        public void Add()
        {
            Load();
            CMSDbDataLayer newDataLayer = new CMSDbDataLayer(string.Empty, CMSDbDataHelper.Microsoft);
            newDataLayer.AddRow(new List<string> { "PluginName" }, new List<string> { theAssembly.FullName }, "CMS_Plugins");
            newDataLayer.SelectQuery = false;
            newDataLayer.Execute();

        }


        public void Remove()
        {
            Load();
            CMSDbDataLayer remove = new CMSDbDataLayer(string.Empty, CMSDbDataHelper.Microsoft);
            remove.DeleteRow(theAssembly.FullName, "PluginName", "CMS_Plugins");
            remove.SelectQuery = true;
            remove.Execute();

        }



        /// <summary>
        /// Gets the assembly.
        /// </summary>
        public Assembly TheAssembly
        {
            get
            {
                return theAssembly;
            }

        }

    }
}
